package org.osami.androidui;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.osami.utils.Logger;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView.ScaleType;

/** An Intent bridge for Hid Manager for querying available devices */
class HidManagerResponseReceiver extends BroadcastReceiver
{
	public final static String INTENT_ACTION_QUERY = "org.osami.HID_MANAGER_QUERY";
	public final static String INTENT_ACTION_RESPONSE = "org.osami.HID_MANAGER_RESPONSE";
	
	Logger log = new Logger(this.getClass().getName());
	
	ServicesListAdapter listmodel;
	
	protected Context androidContext;
	
	public HidManagerResponseReceiver(ServicesListAdapter listmodel)
	{
		this.listmodel = listmodel;
	}
	
	@Override
	public void onReceive(Context context, Intent aIntent) {
 
		Bundle extras = aIntent.getExtras();
		
		if(!extras.containsKey("devices")){
			return;
		}
		
		JSONArray devices;
		this.listmodel.clear();
		 
		try {
			devices = new JSONArray(extras.get("devices")
					.toString());

			int i;
			for (i = 0; i < devices.length(); i++) {
				JSONObject dev = devices.getJSONObject(i);

				String name = dev.getString("name");
				String description = dev.getString("description");

				OsamiServiceInfo info = new OsamiServiceInfo(name, description);
				info.setUiUrl(dev.getString("ui_url"));
				info.setUrlIcon(dev.getString("icon_url"));

				listmodel.add(info);
				
				/*
				 * dev.put("name", "Sauna"); dev.put("id", "sauna-controller");
				 * dev.put("description", "Sauna statusboard");
				 * dev.put("icon_url", "http://192.168.0.106/sauna.png");
				 * dev.put("ui_url", "http://192.168.0.106/sauna.html");
				 */
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


class ServicesListAdapter extends ArrayAdapter<OsamiServiceInfo> 
{

	private ArrayList<OsamiServiceInfo> items;
	
	public ServicesListAdapter(Context context, 
			 int textViewResourceId, 
			 ArrayList<OsamiServiceInfo> items) 
	{
		super(context, textViewResourceId, items);
        this.items = items;
	}
	 
	public int getCount() {
		return this.items.size();
	}

	public OsamiServiceInfo getItem(int position) {
		return this.items.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) 
	{
		View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.service_list_item, null);
        }
        
        OsamiServiceInfo o = this.getItem(position);
        if (o != null) 
        {
            TextView tt = (TextView) v.findViewById(R.id.service_item_name);
            TextView bt = (TextView) v.findViewById(R.id.service_item_description);
            
            ImageView im = (ImageView) v.findViewById(R.id.service_item_icon);
            
            if (tt != null) 
            {
            	tt.setText(o.getName());                            
            }
            
            if(bt != null)
            {
            	bt.setText(o.getDescription());
            }
            
            if(im != null)
            {
            	o.loadIconToView(im,this);
            	/*
            	if(o.getIcon() != null){
            		im.setImageDrawable(o.getIcon());
            	}
            	*/
            	/*
            	// TODO: Asynchronous/cache
            	try {
            		String u = o.getUrlIcon();
            		
            		if(u.length() > 0)
            		{
						URL url = new URL(u);
						if(url != null){
							InputStream content = (InputStream)url.getContent();
							Drawable d = Drawable.createFromStream(content , "src");
							im.setImageDrawable(d);
						}
            		}
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				*/
            }
        }
        
        return v;
	}
}


public class ListFragment extends Fragment {
	
	Context context;
	LinearLayout bottomPanel;
	HidManagerResponseReceiver hidmanagerResponseReceiver;
	
	protected void addBottomIcon(int aResourceID)
	{
		ImageView icon = new ImageView(context);
	    icon.setImageResource(aResourceID);
	    icon.setAdjustViewBounds(true);
	    icon.setScaleType(ScaleType.CENTER_INSIDE);
	    
	    LinearLayout.LayoutParams layoutParams;
	    layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                									 LayoutParams.WRAP_CONTENT);
	    layoutParams.leftMargin = 5;
	    layoutParams.rightMargin = 5;
	    
	    icon.setLayoutParams(layoutParams);
		
	    bottomPanel.addView(icon);
	}
	
	/** Creates a vertical line, which separates the service list and icons bar at the bottom */
	ImageView makeSeparator()
	{
		ImageView separator = new ImageView(context);
	    separator.setImageResource(R.drawable.area_separator);
	    separator.setAdjustViewBounds(true);
	    
	    RelativeLayout.LayoutParams layoutParams;
	    layoutParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
	            									   LayoutParams.WRAP_CONTENT);
	    layoutParams.addRule(RelativeLayout.ABOVE, bottomPanel.getId());
	    layoutParams.bottomMargin = 5;
	    layoutParams.topMargin = 5;
	    
	    separator.setLayoutParams(layoutParams);
	    separator.setScaleType(ScaleType.FIT_XY);
	    
	    return separator;
	    
	}
	
	@Override
	public void onDestroy() {
		context.unregisterReceiver(hidmanagerResponseReceiver);	
		super.onDestroy();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		context = this.getActivity().getBaseContext();
		
		LayoutParams params;		
		RelativeLayout layout;
		
		layout = new RelativeLayout(context);
		params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		layout.setLayoutParams(params);
		 
		// TODO: Get service items from OSGi
		ArrayList<OsamiServiceInfo> items = new ArrayList<OsamiServiceInfo>();
		
		OsamiServiceInfo service;
		
		service = new OsamiServiceInfo("Telly", "TV controller");
		service.setUiUrl("http://10.20.49.113:8080/index.html");
		items.add(service);
		
		service = new OsamiServiceInfo("Sauna", "Sauna statusboard");
		service.setUiUrl("http://192.168.0.102:8080/sauna.html");
		items.add(service);
		
		service = new OsamiServiceInfo("Traffic", "");
		service.setUiUrl("http://192.168.0.102:8080/traffic.html");
		items.add(service);
		
		ServicesListAdapter listmodel = new ServicesListAdapter(context, 0, items);
		 
		final ListView list = new ListView(context);
		list.setAdapter(listmodel);
		list.setOnItemClickListener(new OnItemClickListener() 
        {
            public void onItemClick(AdapterView<?> parent, View view, int position, long i) 
            {
            	OsamiUI activity = (OsamiUI)getActivity();
				activity.listItemSelected((OsamiServiceInfo)list.getAdapter().getItem(position));
				list.setSelection(position);
            }
        });
		
		layout.addView(list);
		
		
		bottomPanel = new LinearLayout(context);
		bottomPanel.setId(0xAAAA);
		
		ImageView separator = makeSeparator();
	    layout.addView(separator);
	    
		// bottom panel		
		layout.addView(bottomPanel);
		
		RelativeLayout.LayoutParams bottomPanelLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,  
                LayoutParams.WRAP_CONTENT);  
		bottomPanelLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);  
        bottomPanel.setLayoutParams(bottomPanelLayoutParams);
        
        addBottomIcon(R.drawable.facebook_icon);
        addBottomIcon(R.drawable.twitter_icon);
        //addBottomIcon(R.drawable.icon);
        
        
        // TODO: Ensure the OSGi runtime is active
		//Intent i = new Intent();		
		//i.setAction("com.prosyst.mbs.android.launcher.MBSServiceStarter");
		//i.setAction("com.prosyst.mbs.LAUNCHER"); // Starts the manager app
		//i.setAction("com.prosyst.mbs.SERVICE");
		
		//startActivity(i);
		//i.setAction("com.prosyst.mbs.STATUS");
		//context.sendBroadcast(i);	
		
        // Create HID Manager intent recever for querying remote devices
        // Each device provides url to html user interface, icon, name, etc
        // HID Manager also provides a query API for querying data and executing operations.
        // Android application communicates with hid manager via Intent API provided via
        // org.osami.appevent bundle. It listens for HidManagerResponseReceiver.INTENT_ACTION_QUERY.
        // For sending parameters, use setExtra(json)
        // TODO: Document possible parameters for operations(sauna controlling, TV program queries)
        // intent and sends responses back via HidManagerResponseReceiver.INTENT_ACTION_RESPONSE intent.
        hidmanagerResponseReceiver = new HidManagerResponseReceiver(listmodel);
		IntentFilter osgiFilter = new IntentFilter(HidManagerResponseReceiver.INTENT_ACTION_RESPONSE);
		context.registerReceiver(hidmanagerResponseReceiver, osgiFilter);
		
		// Query devices
        Intent intent = new Intent();
		intent.setAction(HidManagerResponseReceiver.INTENT_ACTION_QUERY);		
		context.sendBroadcast(intent);
		
		return layout;
	}
}

